<template>
  <!-- 模板代码完全不变，保留原有UI结构 -->
  <div class="btnBox">
    <van-popup :close-on-click-overlay="false" v-model="show.isShow">
      <div
        class="reward-page"
        :style="{ background: currentConfig.mainAreaBg }"
      >
        <van-nav-bar
          :border="false"
          :style="{ background: currentConfig.mainAreaBg }"
        >
          <template #title>
            <div
              class="title"
              :style="{ color: currentConfig.activeTitleColor }"
            >
              为ta加票
            </div>
          </template>
          <template #left>
            <van-icon
              :style="{ color: currentConfig.activeTitleColor }"
              name="revoke"
              size="18"
              @click="closePopue"
            />
          </template>
        </van-nav-bar>

        <!-- 头部信息区域 -->
        <div class="top-info">
          <div class="user-header">
            <van-image
              round
              :src="
                playerInfo.imageUrl?.length
                  ? playerInfo.imageUrl[0]
                  : require('@/assets/list_touxiang.png')
              "
            />
            <div
              class="user-id"
              :style="{ color: currentConfig.activeTitleColor }"
            >
              {{ playerInfo.activityNum }}号--{{ playerInfo.name }}
            </div>
          </div>
          <div
            class="stats-row"
            :style="{
              background: currentConfig.countBg,
              color: currentConfig.count,
            }"
          >
            <div class="stat-item">
              <div class="stat-value">{{ playerInfo.rank }}</div>
              <div class="stat-label">排名</div>
            </div>
            <div class="stat-item">
              <div class="stat-value">{{ playerInfo.voteCount }}</div>
              <div class="stat-label">票数</div>
            </div>
            <div class="stat-item">
              <div class="stat-value">{{ playerInfo.view }}</div>
              <div class="stat-label">浏览量</div>
            </div>
          </div>
        </div>

        <!-- 打赏道具列表 -->
        <div class="gift-list">
          <div
            class="gift-item"
            v-for="(gift, index) in gifts"
            :key="index"
            @click="selectGift(gift)"
            :class="{ selected: selectedGift === gift }"
          >
            <van-image
              width="60px"
              height="60px"
              :src="gift.icon"
              fit="contain"
            />
            <div class="gift-points" :style="currentConfig.button">
              {{ gift.points }}点
            </div>
          </div>
        </div>
      </div>

      <div class="footer">
        <div class="footer-toolbar">
          <div class="price">¥{{ (unitPrice * count).toFixed(2) }}</div>
          <div class="count-control">
            <van-button size="mini" icon="minus" @click="decrement" />
            <!-- 补充：防止输入非正整数 -->
            <input
              type="number"
              v-model.number="count"
              min="1"
              class="count-input"
              @input="handleCountInput"
            />
            <van-button size="mini" icon="plus" @click="increment" />
          </div>
          <van-button
            round
            type="green"
            class="send-btn"
            :disabled="!selectedGift"
            @click="handleSend"
            :style="currentConfig.button"
          >
            立即送出
          </van-button>
        </div>
      </div>
    </van-popup>
  </div>
</template>

<script>
import heic2any from "heic2any"; // 若未使用可删除，此处保留原有依赖
import wx from "weixin-js-sdk"; // 微信JSSDK，用于拉起支付
import { Dialog, Toast } from "vant";
import { getVoteing } from "@/api/index.js"; // 后端支付接口

export default {
  props: ["childrenAddData"],
  data() {
    return {
      comFlag: true,
      show: { isShow: false, buttonStyle: "", type: 0 },
      userLocation: null,
      signUpForm: { name: "", phone: "", declaration: "" },
      playerInfo: {}, // 选手信息
      currentConfig: {}, // 样式配置
      form: {
        tbTestimonials: "",
        tbLongitudeLatitude: "",
        tbLocation: "",
        tbUserid: localStorage.getItem("uuid"),
      },
      showCalender: false,
      minDate: new Date(2025, 0, 1),
      maxDate: new Date(2099, 10, 1),
      currentDate: new Date(),
      wxId: localStorage.getItem("uuid"),
      fileList: [],
      ShowSubMit: false,
      pageSize: 5,
      currentPage: 1,
      isLoading: false,
      hasMoreData: true,
      // 礼物相关
      count: 1, // 选择数量
      gifts: [
        {
          name: "比心",
          icon: require("@/assets/gift_bx.png"),
          points: 20,
          price: 5.0,
        },
        {
          name: "打Call",
          icon: require("@/assets/gift_dc.png"),
          points: 45,
          price: 10.0,
        },
        {
          name: "加油鸭",
          icon: require("@/assets/gift_jy.png"),
          points: 99,
          price: 19.0,
        },
        {
          name: "热气球",
          icon: require("@/assets/gift_rqq.png"),
          points: 260,
          price: 49.0,
        },
        {
          name: "你最好看",
          icon: require("@/assets/gift_nzhk.png"),
          points: 550,
          price: 99.0,
        },
        {
          name: "跑车",
          icon: require("@/assets/gift_pc.png"),
          points: 1200,
          price: 199.0,
        },
        {
          name: "火箭",
          icon: require("@/assets/gift_h.png"),
          points: 3288,
          price: 499.0,
        },
        {
          name: "浪漫城堡",
          icon: require("@/assets/gift_lm.png"),
          points: 5688,
          price: 699.0,
        },
        {
          name: "嘉年华",
          icon: require("@/assets/gift_j.png"),
          points: 8888,
          price: 999.0,
        },
      ],
      selectedGift: null, // 当前选中礼物
      unitPrice: 0, // 单价
      outTradeNo: "", // 存储订单号（用于后续查询/对账）
      wxConfigReady: false, // 标记JS-SDK是否初始化成功
    };
  },
  watch: {
    // 监听父组件传递的弹窗显示状态
    childrenAddData: {
      deep: true,
      handler(newVal) {
        if (newVal) {
          this.show.isShow = newVal.show;
          this.playerInfo = newVal.playerItem || {};
          this.currentConfig = newVal.passCurrentConfig || {};
        }
      },
    },
  },
  methods: {
    // 补充：限制数量为正整数（防止异常输入）
    handleCountInput() {
      if (this.count < 1) this.count = 1;
      if (!Number.isInteger(this.count)) this.count = Math.floor(this.count);
    },

    // 数量减少
    decrement() {
      if (this.count > 1) this.count--;
    },

    // 数量增加
    increment() {
      this.count++;
    },

    // 选择礼物（同步单价和重置数量）
    selectGift(gift) {
      this.selectedGift = gift;
      this.unitPrice = gift.price;
      this.count = 1;
    },

    // 核心：立即送出（调用接口+拉起微信支付）
    // 核心：立即送出（从payInfo提取微信配置）
    async handleSend() {
      // 1. 基础校验
      if (!this.selectedGift) {
        Toast("请选择要赠送的礼物");
        return;
      }
      const openId = localStorage.getItem("openId") || "";
      if (!openId) {
        Toast("信息缺失，请重新进入页面");
        return;
      }

      // 2. 支付确认弹窗
      try {
        await Dialog.confirm({
          title: "确认支付",
          message: `将支付 ¥${(this.selectedGift.price * this.count).toFixed(
            2
          )}，为选手增加 ${this.selectedGift.points * this.count} 票`,
          confirmButtonText: "确认支付",
          cancelButtonText: "取消",
        });
      } catch (error) {
        Toast(error.message);
        return;
      }

      // 3. 调用后端接口，获取payInfo（包含微信配置和支付参数）
      Toast.loading({ message: "处理中...", forbidClick: true, duration: 0 });
      try {
        const paidVoteParams = {
          participantId: this.playerInfo.id,
          voterOpenId: openId,
          voteCount: this.selectedGift.points * this.count,
          voteType: "gift",
          giftName: this.selectedGift.name,
          giftAmount: (this.selectedGift.price * this.count).toFixed(2),
        };

        const response = await getVoteing(paidVoteParams);
        const resData = response.data;

        // 4. 接口响应基础校验
        if (resData?.code != 0) {
          throw new Error(resData?.msg || "获取支付信息失败");
        }
        const {
          timeStamp,
          nonceStr,
          package: prepayPackage,
          signType,
          paySign,
        } = resData.data.payInfo;
        const { appid  } = resData.data;
        console.log("🚀 ~ handleSend ~ resData.payInfo:", resData.data.payInfo);
        // 6. 校验所有必需参数（含双重作用的paySign）
        const requiredConfigFields = [appid, timeStamp, nonceStr, paySign]; // paySign即signature
        const requiredPayFields = [
          timeStamp,
          nonceStr,
          prepayPackage,
          signType,
          paySign,
        ];
        if (requiredConfigFields.some((field) => !field)) {
          throw new Error(
            "payInfo中缺少微信环境配置参数（appid/timeStamp/nonceStr/paySign）"
          );
        }
        if (requiredPayFields.some((field) => !field)) {
          throw new Error(
            "payInfo中缺少支付参数（timeStamp/nonceStr/package等）"
          );
        }

        // 7. 初始化微信JS-SDK环境（需要重新获取JS-SDK签名）
        // 注意：paySign是支付签名，不能直接用作JS-SDK的signature
        // 需要调用后端接口获取JS-SDK签名
        const jsConfigResponse = await this.getWxJsConfig();
        if (jsConfigResponse.data.code !== 0) {
          throw new Error("获取微信JS-SDK配置失败");
        }
        
        await this.initWxConfig(jsConfigResponse.data.data);

        // 8. 拉起微信支付（用payInfo中的支付参数）
        wx.chooseWXPay({
          timeStamp: timeStamp,
          nonceStr: nonceStr,
          package: prepayPackage,
          signType: signType,
          paySign: paySign, // 支付签名仍用paySign
          success: (res) => {
            if (res.errMsg === "chooseWXPay:ok") {
              this.handleVoteSuccess();
            }
          },
          fail: (err) => {
            Toast.fail(`支付失败：${err.errMsg || "未知错误"}`);
            console.error("微信支付失败：", err);
          },
          cancel: () => {
            Toast("已取消支付");
          },
        });
      } catch (error) {
        Toast.fail(error.message || "操作失败，请重试");
        console.error("支付流程异常：", error);
      } finally {
        Toast.clear();
      }
    },

    // 获取微信JS-SDK配置
    async getWxJsConfig() {
      const url = window.location.href.split('#')[0]; // 当前页面URL
      const response = await fetch('/app/wechat/js-config', {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json',
        },
        body: JSON.stringify({ url: url })
      });
      return response.json();
    },

    // 初始化微信JS-SDK（参数来自专门的JS-SDK接口）
    initWxConfig(config) {
      return new Promise((resolve, reject) => {
        wx.config({
          debug: false, // 生产环境关闭调试
          appId: config.appId,
          timestamp: config.timestamp,
          nonceStr: config.nonceStr,
          signature: config.signature, // 使用正确的JS-SDK签名
          jsApiList: ["chooseWXPay"],
        });

        // 监听初始化成功
        wx.ready(() => {
          console.log("微信JS-SDK初始化成功");
          this.wxConfigReady = true;
          resolve();
        });

        // 监听初始化失败（常见：签名错误、appId不匹配）
        wx.error((err) => {
          console.error("微信JS-SDK初始化失败：", err);
          let errorMsg = "支付环境初始化失败";
          if (err.errMsg.includes("invalid signature")) {
            errorMsg =
              "签名错误（paySign作为signature不符合微信规范，建议后端检查）";
          } else if (err.errMsg.includes("appid not exist")) {
            errorMsg = "appId不存在，请检查公众号配置";
          }
          reject(new Error(errorMsg));
        });
      });
    },

    handleVoteSuccess() {
      Toast.success("支付成功！票数已增加");
      this.$emit("update-player-vote", {
        playerId: this.playerInfo.id,
        newVoteCount:
          this.playerInfo.voteCount + this.selectedGift.points * this.count,
      });
      this.closePopue();
    },

    // 跳转详情（原有方法，保留）
    goDetails() {
      this.show.isShow = false;
      this.$emit("child-event", this.show);
    },

    // 显示报名弹窗（原有方法，保留）
    showPerPopup() {
      this.passPerData = { show: true, buttonStyle: this.buttonStyle };
    },

    // 关闭支付弹窗
    closePopue() {
      this.show.isShow = false;
      this.$emit("AddTickets-event", this.show);
      // 重置选择状态（下次打开弹窗时恢复初始状态）
      this.selectedGift = null;
      this.count = 1;
    },
  },
};
</script>

<style scoped lang="less">
.van-popup {
  width: 100%;
  height: 100vh;
  display: flex;
  flex-direction: column;
  background: #fff;
  font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, sans-serif;
}

.title {
  color: #666;
}

.icon {
  color: #666;
  font-size: 18px;
}

::v-deep .van-image {
  display: block;
  width: 100px;
  height: 100px;
  overflow: hidden;
}

::v-deep .van-uploader__wrapper {
  width: 100%;
}

::v-deep .van-uploader__upload {
  width: 100px;
  height: 100px;
}

::v-deep .van-uploader__preview,
.van-uploader__upload {
  margin: 0 6px 6px 0;
}

::v-deep .van-cell--clickable {
  margin-top: 25px;
  border: 1px solid #eceaea;
}

.location {
  color: #666;
  font-size: 16px;
  margin: 10px 0px 0px 20px;
}

.dateClass {
  border-bottom: 1px solid #f4f4f4;
}

::v-deep .van-cell__value {
  text-align: left;
}

::v-deep .van-cell__title,
.van-cell__value {
  -webkit-box-flex: 1;
}

::v-deep .van-uploader__file {
  width: 100px;
  height: 100px;
}

.locationBer {
  width: 70%;
}

.dataBer {
  height: 32px;
  line-height: 32px;
  margin-right: 18px;
}

::v-deep .van-cell {
  color: #323233 !important;
  background-color: #fff !important;
}

.wrapper {
  display: flex;
  align-items: center;
  justify-content: center;
  height: 100%;
}

.block {
  width: 120px;
  height: 120px;
  background-color: #fff;
}

.details_content {
  flex: 1;
  overflow-y: auto;
  -webkit-overflow-scrolling: touch;
  padding-bottom: 70px;
  background-color: #eaeff3;
}
.details_box {
  width: 100%;
  height: 300px;
  border: 1px solid #000;
}

/* 头部信息区域 */
.top-info {
  padding: 10px;
  .user-header {
    display: flex;
    flex-direction: column;
    align-items: center;
    .user-id {
      margin: 10px 0;
      font-size: 14px;
      color: #333;
    }
  }
  .stats-row {
    display: flex;
    justify-content: space-around;
    background-color: #07c160;
    color: #fff;
    border-radius: 8px;
    margin-top: 10px;
    padding: 8px 0;
    .stat-item {
      text-align: center;
      .stat-value {
        font-size: 16px;
        font-weight: bold;
        margin-bottom: 4px;
      }
      .stat-label {
        font-size: 12px;
      }
    }
  }
}

.reward-page {
  flex: 1;
  overflow-y: auto;
  -webkit-overflow-scrolling: touch;
  padding-bottom: 70px;
  background-color: #eaeff3;

  .header {
    display: flex;
    align-items: center;
    margin-bottom: 15px;
    .user-info {
      margin-left: 10px;
      .user-id {
        font-size: 14px;
        color: #333;
        margin-bottom: 5px;
      }
      .stats {
        display: flex;
        color: #fff;
        background-color: #07c160;
        border-radius: 8px;
        overflow: hidden;
        .stat-item {
          flex: 1;
          text-align: center;
          padding: 4px 0;
          &:not(:last-child) {
            border-right: 1px solid #fff;
          }
          .value {
            font-size: 16px;
            font-weight: bold;
            display: block;
          }
          .label {
            font-size: 12px;
          }
        }
      }
    }
  }

  .gift-list {
    display: flex;
    flex-wrap: wrap;
    justify-content: space-around;
    margin: 5px;
    .gift-item {
      width: 30%;
      text-align: center;
      margin-bottom: 10px;
      display: flex;
      flex-direction: column;
      align-items: center;
      background-color: #fff;
      border-radius: 10px;
      padding: 10px 0;
      transition: all 0.2s ease;
      cursor: pointer;

      // 选中高亮样式
      &.selected {
        background-color: #ededed;
        border: 1px solid #07c160;
        transform: scale(1.05);
      }

      .gift-name {
        font-size: 14px;
        color: #738593;
        margin-bottom: 5px;
      }
      .gift-points {
        font-size: 12px;
        color: #fff;
        width: 100%;
        background-color: #07c160;
        padding: 3px 0;
        margin-top: 5px;
      }
    }
  }
}

/* 底部操作栏 */
.footer-toolbar {
  width: 100%;
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 0 10px;
  height: 50px;

  .price {
    font-size: 16px;
    color: #e63946;
    font-weight: bold;
  }

  .count-control {
    display: flex;
    align-items: center;

    .count-input {
      width: 50px;
      height: 30px;
      text-align: center;
      border: 1px solid #eee;
      border-radius: 4px;
      margin: 0 5px;
      padding: 0;
    }
  }

  .send-btn {
    background-color: #07c160;
    color: #fff;
    padding: 0 20px;
    height: 36px;
    &:disabled {
      background-color: #ccc;
      cursor: not-allowed;
    }
  }
}

.footer {
  position: fixed;
  bottom: 0;
  left: 0;
  right: 0;
  height: 50px;
  background-color: #fff;
  box-shadow: 0 -2px 10px rgba(0, 0, 0, 0.05);
  display: flex;
  z-index: 100;
  justify-content: space-between;
  align-items: center;
  padding: 0px 10px;

  .comBar {
    font-weight: 500;
    font-size: 16px;
    span {
      display: inline-block;
      height: 30px;
      line-height: 30px;
    }
    .tetx {
      margin: 15px 0px 15px 0px;
    }
  }

  .shouye {
    img {
      width: 23px;
      margin-right: 5px;
    }
  }

  .vote-btn {
    position: absolute;
    left: 50%;
    top: -30px;
    transform: translateX(-50%);
    width: 60px;
    height: 60px;
    line-height: 60px;
    text-align: center;
    background-color: #07c160;
    color: #fff;
    border-radius: 50%;
    font-size: 16px;
    font-weight: 600;
    box-shadow: 0 2px 8px rgba(0, 0, 0, 0.2);
    &:active {
      opacity: 0.8;
    }
  }

  .jiapiao {
    img {
      width: 34px;
      margin: 13px 0px;
    }
  }
}

::v-deep .van-image {
  width: 60px;
  height: 60px;
  margin: 5px 0;
}

::v-deep .van-button--small {
  height: 30px;
  padding: 0 10px;
  font-size: 12px;
}

::v-deep .van-nav-bar {
  background-color: #eaeff3;
}

/* 修复按钮图标位置 */
::v-deep .van-button__icon {
  display: flex;
  align-items: center;
  justify-content: center;
}
</style>
